package com.manli.api.service;

import com.manli.api.base.exception.MyException;
import com.manli.api.pojo.QueryParamsUserPass;
import com.manli.api.util.*;
import org.beetl.sql.core.SQLManager;
import org.springframework.stereotype.Service;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import java.util.List;
import com.manli.api.pojo.Result;
import com.manli.api.pojo.SessionInfo;

import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import com.manli.api.dao.UserDao;
import com.manli.api.dto.User;
import org.springframework.transaction.annotation.Transactional;


@Service("userService")
public class UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    SQLManager sqlManager;
    @Autowired
    SessionInfoUtils sessionInfoUtils;
    @Autowired
    AliYunSmsUtil aliYunSmsUtil;

    
    public Result queryPage(Map<String, Object> params) {
        PageQuery<User> page = userDao.createQuery()
                .page(Long.parseLong(params.get("page").toString()),Long.parseLong(params.get("limit").toString()));
        return ResultUtil.success(page.getList(),page.getTotalRow());
    }

    
    public Result queryAll() {
        List<User> list = userDao.all();
        return ResultUtil.success(list);
    }

    
    public Result getById(Integer userId) {
        User user = userDao.single(userId);
        return ResultUtil.success(user);
    }

    public User getUserById(Integer userId) {
        User user = userDao.single(userId);
        return user;
    }

    @Transactional
    public Result save(User user,HttpServletRequest request) {
    	SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
    	user.setBranchId(sessionInfo.getBranchId());

        //判断值为空
        ObjectEmptyUtil.userIsEmpty(user);

        userDao.insert(user);
        return ResultUtil.success();
    }

    @Transactional
    public Result updateById(User user) {
        //判断值为空
        ObjectEmptyUtil.userIsEmpty(user);

        userDao.updateTemplateById(user);
        return ResultUtil.success();
    }

    @Transactional
    public Result removeById(Integer userId) {
        userDao.deleteById(userId);
        return ResultUtil.success();
    }

    @Transactional
    public Result removeByIds(List<Integer> ids) {
        for (Integer id:ids) {
            userDao.deleteById(id);
        }
        return ResultUtil.success();
    }

    @Transactional
    public Result passwordUpdate(User user) throws Exception{
        //判断值为空
        ObjectEmptyUtil.userIsEmptyPass(user);
        String sql = "select * from user where username = '" + user.getUsername() + "'";
        List<User> list = userDao.execute(sql);
        if(list.size() == 0){
            throw new MyException(-1,"用户不存在");
        }
        User user1 = list.get(0);
        //号码是否一致
        if(user.getUserPhone().equals(user1.getUserPhone())){
            //验证码是否一致
            if(aliYunSmsUtil.phoneCodeIsPass(user.getUserPhone(),user.getPhoneCode())){
                String sql1 = "update user set password = '" + Encrypt.encrypt(user.getPassword()) + "' where user_id = " + user1.getUserId();
                userDao.executeUpdate(sql1);
            }

        }else{
            throw new MyException(-1,"手机号码与原账号不一致");
        }
        return ResultUtil.success();
    }

    @Transactional
    public Result passwordUpdateLogin(QueryParamsUserPass pass, HttpServletRequest request) throws Exception{
        //判断值为空
        ObjectEmptyUtil.passwordUpdateLogin(pass);

        SessionInfo sessionInfo = sessionInfoUtils.getSessionInfoByAuth(request);
        Integer userid = sessionInfo.getUserId();
        String sql = "select * from user where user_id = " + userid;
        List<User> list = userDao.execute(sql);
        if(list.size() == 0){
            throw new MyException(-1,"用户不存在");
        }
        User user1 = list.get(0);
        //新旧密码是否一致
        if(pass.getLastPassword().equals(pass.getNewPassword())){
            throw new MyException(-1,"新旧密码一致，请重新输入");
        }
        if(!Encrypt.encrypt(pass.getLastPassword()).equals(user1.getPassword())){
            throw new MyException(-1,"旧密码错误");
        }

        //号码是否一致
        if(pass.getUserPhone().equals(user1.getUserPhone())){
            //验证码是否一致
            if(aliYunSmsUtil.phoneCodeIsPass(pass.getUserPhone(),pass.getPhoneCode())){
                String sql1 = "update user set password = '" + Encrypt.encrypt(pass.getNewPassword()) + "' where user_id = " + user1.getUserId();
                userDao.executeUpdate(sql1);
            }

        }else{
            throw new MyException(-1,"手机号码与原账号不一致");
        }
        return ResultUtil.success();

    }
}
